package com.young.commom.httpclient.okhttp;

import com.young.commom.httpclient.AbstractHttpClientTemplate;
import com.young.commom.httpclient.HttpClientConfiguration;
import com.young.commom.httpclient.HttpResult;
import com.young.common.core.util.Utils;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @description：
 * @author: yangyahui01
 * @date: 11/29/24 1:04 PM
 */
public class OkHttpClientTemplate extends AbstractHttpClientTemplate {
    private OkHttpClient httpClient;
    private volatile boolean init = false;
    private List<Interceptor> interceptors;

    public void setInterceptors(List<Interceptor> interceptors) {
        this.interceptors = interceptors;
    }

    public OkHttpClientTemplate() {
    }

    public OkHttpClientTemplate(HttpClientConfiguration configuration) {
        super(configuration);
    }

    public synchronized void init() {
        if (!this.init) {
            super.init();
            if (this.interceptors == null) {
                this.interceptors = new ArrayList();
            }

            OKHttpHttpRequestInterceptor interceptor = new OKHttpHttpRequestInterceptor();
            if (this.configuration.isDnsResolverEnabled()) {
                interceptor.setDnsResolver(this.configuration.getNamingResolver());
            }

            interceptor.setGlobalHeaders(this.configuration.getGlobalHeaders());
            this.interceptors.add(interceptor);
            this.httpClient = OkHttpClientBuilder.build(this.getConfiguration(), this.interceptors);
            this.init = true;
        }
    }

    public HttpResult get(String uri) {
        return this.get(uri, (Map)null);
    }

    public HttpResult get(String uri, Map<String, String> parameters) {
        return this.get(uri, parameters, (Map)null);
    }

    public HttpResult get(String uri, Map<String, String> parameters, Map<String, String> headers) {
        if (StringUtils.isBlank(uri)) {
            return null;
        } else {
            try {
                Request.Builder builder = new Request.Builder();
                builder.url(Utils.url(uri, parameters, this.charset));
                builder.header("Content-type", MessageFormat.format("application/json; charset={0}", this.charset));
                this.headers(builder, headers);
                Request request = builder.get().build();
                return this.process(request);
            } catch (Exception var6) {
                throw new RuntimeException("HttpClient error.", var6);
            }
        }
    }

    private void headers(Request.Builder builder, Map<String, String> headers) {
        if (headers != null && !headers.isEmpty()) {
            Iterator var3 = headers.entrySet().iterator();

            while(var3.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var3.next();
                String value = entry.getValue() == null ? "" : (String)entry.getValue();
                builder.header((String)entry.getKey(), value);
            }

        }
    }

    public HttpResult post(String uri) {
        if (StringUtils.isBlank(uri)) {
            return null;
        } else {
            try {
                Request.Builder builder = new Request.Builder();
                builder.url(uri);
                String contentType = MessageFormat.format("application/json; charset={0}", this.charset);
                RequestBody body = RequestBody.create(MediaType.parse(contentType), "");
                builder.post(body);
                Request request = builder.build();
                return this.process(request);
            } catch (Exception var6) {
                throw new RuntimeException("HttpClient error.", var6);
            }
        }
    }

    public HttpResult post(String uri, String content) {
        return this.postBody(uri, content, (Map)null, (Map)null);
    }

    public HttpResult post(String uri, String content, Map<String, String> parameters) {
        return this.postBody(uri, content, parameters, (Map)null);
    }

    public HttpResult post(String uri, String content, Map<String, String> parameters, Map<String, String> headers) {
        return this.postBody(uri, content, parameters, headers);
    }

    private HttpResult postBody(String uri, String content, Map<String, String> parameters, Map<String, String> headers) {
        if (StringUtils.isBlank(uri)) {
            return null;
        } else {
            try {
                Request.Builder builder = new Request.Builder();
                builder.url(Utils.url(uri, parameters, this.charset));
                String contentType = MessageFormat.format("application/json; charset={0}", this.charset);
                RequestBody body = RequestBody.create(MediaType.parse(contentType), content == null ? "" : content);
                this.headers(builder, headers);
                builder.post(body);
                Request request = builder.build();
                return this.process(request);
            } catch (Exception var9) {
                throw new RuntimeException("HttpClient error.", var9);
            }
        }
    }

    public HttpResult post(String uri, Map<String, String> parameters) {
        return this.postForm(uri, parameters, (Map)null);
    }

    public HttpResult post(String uri, Map<String, String> parameters, Map<String, String> headers) {
        return this.postForm(uri, parameters, headers);
    }

    private HttpResult postForm(String uri, Map<String, String> parameters, Map<String, String> headers) {
        if (StringUtils.isBlank(uri)) {
            return null;
        } else {
            try {
                Request.Builder builder = new Request.Builder();
                builder.url(uri);
                okhttp3.FormBody.Builder fb = new okhttp3.FormBody.Builder(Charset.forName(this.charset));
                if (parameters != null) {
                    parameters.forEach((k, v) -> {
                        fb.addEncoded(k, v);
                    });
                }

                this.headers(builder, headers);
                builder.post(fb.build());
                Request request = builder.build();
                return this.process(request);
            } catch (Exception var7) {
                throw new RuntimeException("HttpClient error.", var7);
            }
        }
    }

    private HttpResult process(Request request) throws Exception {
        HttpResult result = new HttpResult();
        Response response = this.httpClient.newCall(request).execute();
        Throwable var4 = null;

        HttpResult var17;
        try {
            int statusCode = response.code();
            result.setCode(statusCode);
            if (response.isSuccessful()) {
                ResponseBody body = response.body();
                if (body != null) {
                    result.setContent(body.string());
                }
            }

            var17 = result;
        } catch (Throwable var15) {
            var4 = var15;
            throw var15;
        } finally {
            if (response != null) {
                if (var4 != null) {
                    try {
                        response.close();
                    } catch (Throwable var14) {
                        var4.addSuppressed(var14);
                    }
                } else {
                    response.close();
                }
            }

        }

        return var17;
    }

    public OkHttpClient getClient() {
        return this.httpClient;
    }

    public String clientType() {
        return "okHttp";
    }

    public void close() {
        if (this.httpClient != null) {
            this.httpClient.dispatcher().executorService().shutdown();
            this.httpClient.connectionPool().evictAll();
        }

    }
}